<script lang="ts">
  import { getContext } from "svelte";
  import { PenLine } from "lucide-svelte";
  import type { Store as ToastStore } from "@zag-js/toast";

  const toast: ToastStore = getContext("toast");

  export interface Option {
    label: string;
    value: string;
  }

  interface Props {
    value: string;
    optionList: Option[];
    canEdit: boolean;
    widthClass: string;
    onChange: (value: string) => Promise<boolean>;
  }

  let props: Props = $props();

  let inEdit = $state(false);

  async function changeValue(value: string) {
    const ok = await props.onChange(value);
    if (ok == false) {
      toast.create({
        title: "失败",
        description: "设置失败!",
        type: "error",
      });
    } else {
      inEdit = false;
    }
  }
</script>

{#if inEdit == false}
  {#each props.optionList as option}
    {#if option.value == props.value}
      <div class={`flex gap-x-2 ${props.widthClass}`}>
        {option.label}
        {#if props.canEdit}
          <button
            type="button"
            class="btn p-0 h-[1rem] hover:preset-tonal"
            onclick={() => (inEdit = true)}
          >
            <PenLine size={16} />
          </button>
        {/if}
      </div>
    {/if}
  {/each}
{:else}
  <select
    class={`select rounded-none bg-surface-100-900 ${props.widthClass}`}
    value={props.value}
    onchange={(e) => changeValue(e.currentTarget.value)}
    onblur={() => (inEdit = false)}
  >
    {#each props.optionList as option}
      <option value={option.value} class="flex gap-x-2">
        {option.label}
      </option>
    {/each}
  </select>
{/if}
